//
//  AYHomeViewController.swift
//  iOSSinaWeb
//
//  Created by yws on 16/5/9.
//  Copyright © 2016年 yws. All rights reserved.
//

import UIKit
import SVPullToRefresh


class AYHomeViewController: AYBaseTabViewController {

    private let reuseIdentifier = "Cell"
    
    var statuses: [AYStatus]? {
        didSet {
//            AMPrint(items: "刷新页面-----")
            self.tableView.reloadData()
        }
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !AYUserAccountViewModel.sharedInstance.isUserLogin {
            return
        }
        setupNavigationBar()
        
        prepareTableView()
    }
    
    
    private func prepareTableView() {
        tableView.registerClass(AYStatusCell.self, forCellReuseIdentifier: reuseIdentifier)
        
        ///预估行高
        tableView.estimatedRowHeight = 200
        
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        
        tableView.addSubview(pullDownToRefreshControl)
        
        pullDownToRefreshControl.pullDownToRefreshCallback = {
            self.loadNewStatus()
        }
        
        //一开始进入就刷新一遍
        pullDownToRefreshControl.beginRefreshing()
        
        
        tableView.addInfiniteScrollingWithActionHandler { 
            self.loadMoreStatus()
        }
        
    }
    
    ///加载更多数据
    private func loadMoreStatus() {
        let max_id = self.statuses?.last?.id ?? 0
        
        AYStatusViewModel.sharedInstance.loadStatus(0, max_id: max_id) { (statuses, error) in
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                AMPrint(items: "上拉加载出错")
                return
            }
            
            let count = statuses?.count ?? 0
            
            if count == 0 {
                return
            }
            
            self.statuses = self.statuses! + statuses!
        }
    }
    
    ///加载新的数据
    private func loadNewStatus() {
        let since_id = self.statuses?.first?.id ?? 0
        
        AYStatusViewModel.sharedInstance.loadStatus(since_id, max_id: 0){ (statuses, error) in
            self.pullDownToRefreshControl.endRefresh()
            
            if error != nil {
                AMPrint(items: "数据刷新加载出错")
                return
            }
            
            let count = statuses?.count ?? 0
            
            if count == 0 {
                return
            }
            
            if since_id == 0 {
                self.statuses = statuses
            } else {
                self.statuses = statuses! + self.statuses!
            }
            
        }
        

    }


    private func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "didClickFriendsearch")
      
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "didClickPop")
        
        

        //获取用户的名称
        let name = AYUserAccountViewModel.sharedInstance.userAccount?.screen_name ?? "未知名称"
        
        
        let button = AYHomeTitleButton()
        button.setTitle(name, forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(16)
        button.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        button.addTarget(self, action: "didClickTitlView:", forControlEvents: UIControlEvents.TouchUpInside)
        button.sizeToFit()
        
        navigationItem.titleView = button
    }
    
    
    
    // MARK: - 点击事件
   func didClickFriendsearch() {
        AMPrint(items: "点击了左边")
    }
    
   func didClickPop() {
        AMPrint(items: "点击了右边")
    let file = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
    let data = NSData(contentsOfFile: file)!
    let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
    
    AMPrint(items: "\(json)")
    
    
    }
    
    
    
    
    
    
    
    func didClickTitlView(button: UIButton) {
        
        button.selected = !button.selected
        
//        UIView.animateWithDuration(0.25) { () -> Void in
            let transfrom = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) : CGAffineTransformIdentity
            
            button.imageView?.transform = transfrom
//        }
        
    }
    
    
    

// MARK: - Lazy

      private lazy var pullDownToRefreshControl: AYPullDownToRefreshControl = AYPullDownToRefreshControl()

}


// MARK: - 扩展

extension AYHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        AMPrint(items: "行数\(statuses?.count)")

        return statuses?.count ?? 0
            }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! AYStatusCell
        
        let status = statuses![indexPath.row]
        
//        AMPrint(items: "status\(status)")
        cell.status = status
        
        
        return cell
    }
    
    
}



